package soul.resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import soul.utils.DateUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by szj on 2017/2/4.
 */
@Controller
@RequestMapping("/file")
public class FileResource {
    public static final String FILE_PATH = "/var/upload/";

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam(value = "photo") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        File tempFile = new File(FILE_PATH, DateUtils.now().getTime() + String.valueOf(fileName));
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        return FILE_PATH + tempFile.getName();
    }

    @GetMapping("/export")
    public void exportCsv(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("gb2312");
        response.setContentType("application/oct-stream");
        response.setHeader("Content-disposition", "attachment;filename=soulk"
                + DateUtils.formatDate(DateUtils.now(), DateUtils.yyyyMMddHHmm) + ".csv");
        PrintWriter writer = response.getWriter();
        //write something...
        response.getWriter().flush();
    }
}